package main

import (
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
)

var workPath string = "/home/www/bilibili"

func main() {
	res := make(chan *string, 25)
	code := make(chan int)
	handle := func(w http.ResponseWriter, r *http.Request) {
		go worker(res, code, r)
		w.WriteHeader(<-code)
		_,_ = io.WriteString(w, *<-res)
	}
	http.HandleFunc("/", handle)
	_ = http.ListenAndServe("127.0.0.1:3535", nil)
}

func worker(res chan *string, code chan int, r *http.Request) {
	req_url := string(r.RequestURI)
	serverError := "Server Error"
	notFound := "Not Found"
	if s, err := os.Stat(workPath + req_url); err == nil {
		if s.IsDir() {
			if req_url != "/" {
				req_url = req_url + "/"
			}
			fileList, err := ioutil.ReadDir(workPath + req_url)
			if err != nil {
				code <- 500
				res <- &serverError
			}
			resList := "<!DOCTYPE html><html><head><meta name='viewport' content='width=device-width,initial-scale=1'><link href='/favicon.ico' rel='shortcut icon' type='image/x-icon' /><title>Go 1.12</title><style>a{color:#999999;text-decoration:none}body,html{padding:0;margin:0;text-align:center;width:100%}</style></head><body><div style='width:85%;margin:15px auto'>"
			for _, v := range fileList {
				file_name := v.Name()
				resList += "<a href='" + req_url + file_name + "'>" + file_name + "</a><br>"
			}
			resList += "</div></body></html>"
			code <- 200
			res <- &resList
		} else {
			file, err := os.Open(workPath + req_url)
			if err != nil {
				code <- 404
				res <- &notFound
				return
			}
			ress, err := ioutil.ReadAll(file)
			if err != nil {
				code <- 500
				res <- &serverError
			} else {
				result := "<!DOCTYPE html><html><head><meta name='viewport' content='width=device-width,initial-scale=1'><link href='/favicon.ico' rel='shortcut icon' type='image/x-icon' /><title>Go 1.12</title><style>body,html{padding:0;margin:0;text-align:center;background:#000022;color:#00CC00}</style></head><body><div style='margin:0 auto;text-align:left;padding:15px'>"
				newRess := strings.ReplaceAll(string(ress), " ", "&nbsp;")
				newRess = strings.ReplaceAll(newRess, "\t", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;")
				result += newRess + "</div></body></html>"
				result = strings.ReplaceAll(result, "\n", "<br>")
				code <- 200
				res <- &result
			}
		}
	} else {
		code <- 404
		res <- &notFound
	}
}
